﻿import { useState, useRef, useEffect } from "react"
import { useTimerState } from "../utils/hooks"

interface Timer {
  id: string
  name: string
  duration: number // 秒
  remaining: number // 秒
  isRunning: boolean
  isCompleted: boolean
  createdAt: Date
}

export default function TimerTab() {
  const [newTimerName, setNewTimerName] = useState('')
  const [newTimerMinutes, setNewTimerMinutes] = useState(5)
  const intervalRef = useRef<NodeJS.Timeout | null>(null)

  // 使用持久化状态管理定时器
  const {
    timers,
    isLoading: timersLoading,
    saveTimers
  } = useTimerState()

  // 定时器管理
  useEffect(() => {
    if (timers.some(timer => timer.isRunning)) {
      intervalRef.current = setInterval(() => {
        const updatedTimers = timers.map(timer => {
          if (timer.isRunning && timer.remaining > 0) {
            const newRemaining = timer.remaining - 1
            if (newRemaining <= 0) {
              // 定时器完成
              chrome.notifications?.create({
                type: 'basic',
                iconUrl: '/assets/icon.png',
                title: '定时器提醒',
                message: `"${timer.name}" 已完成！`
              })
              return { ...timer, remaining: 0, isRunning: false, isCompleted: true }
            }
            return { ...timer, remaining: newRemaining }
          }
          return timer
        })
        
        // 保存更新后的定时器状态
        saveTimers(updatedTimers)
      }, 1000)
    } else {
      if (intervalRef.current) {
        clearInterval(intervalRef.current)
        intervalRef.current = null
      }
    }

    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current)
      }
    }
  }, [timers, saveTimers])

  // 格式化时间显示
  const formatTime = (seconds: number): string => {
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    const secs = seconds % 60
    
    if (hours > 0) {
      return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
    }
    return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }

  // 添加新定时器
  const addTimer = async () => {
    if (!newTimerName.trim()) {
      alert('请输入定时器名称！')
      return
    }
    
    if (newTimerMinutes <= 0) {
      alert('定时器时间必须大于0！')
      return
    }

    const newTimer: Timer = {
      id: Date.now().toString(),
      name: newTimerName.trim(),
      duration: newTimerMinutes * 60,
      remaining: newTimerMinutes * 60,
      isRunning: false,
      isCompleted: false,
      createdAt: new Date()
    }

    const updatedTimers = [...timers, newTimer]
    await saveTimers(updatedTimers)
    
    setNewTimerName('')
    setNewTimerMinutes(5)
  }

  // 开始/暂停定时器
  const toggleTimer = async (id: string) => {
    const updatedTimers = timers.map(timer => 
      timer.id === id 
        ? { ...timer, isRunning: !timer.isRunning }
        : timer
    )
    await saveTimers(updatedTimers)
  }

  // 重置定时器
  const resetTimer = async (id: string) => {
    const updatedTimers = timers.map(timer => 
      timer.id === id 
        ? { ...timer, remaining: timer.duration, isRunning: false, isCompleted: false }
        : timer
    )
    await saveTimers(updatedTimers)
  }

  // 删除定时器
  const deleteTimer = async (id: string) => {
    const updatedTimers = timers.filter(timer => timer.id !== id)
    await saveTimers(updatedTimers)
  }

  // 清空所有定时器
  const clearAllTimers = async () => {
    if (timers.length === 0) return
    if (confirm('确定要清空所有定时器吗？')) {
      await saveTimers([])
    }
  }

  return (
    <div>
      <h3 style={{ marginTop: 0, color: "#333" }}>
         多任务定时器
      </h3>

      {/* 添加新定时器 */}
      <div style={{ 
        padding: '12px', 
        backgroundColor: '#f8f9fa', 
        borderRadius: '6px', 
        marginBottom: 16,
        border: '1px solid #ddd'
      }}>
        <div style={{ marginBottom: 8 }}>
          <input
            type="text"
            placeholder="定时器名称"
            value={newTimerName}
            onChange={(e) => setNewTimerName(e.target.value)}
            style={{
              width: '100%',
              padding: '8px',
              border: '1px solid #ddd',
              borderRadius: '4px',
              fontSize: '14px',
              marginBottom: '8px'
            }}
          />
        </div>
        <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
          <input
            type="number"
            min="1"
            max="1440"
            value={newTimerMinutes}
            onChange={(e) => setNewTimerMinutes(Number(e.target.value))}
            style={{
              width: '80px',
              padding: '8px',
              border: '1px solid #ddd',
              borderRadius: '4px',
              fontSize: '14px'
            }}
          />
          <span style={{ fontSize: '14px', color: '#666' }}>分钟</span>
          <button
            onClick={addTimer}
            style={{
              flex: 1,
              padding: '8px 12px',
              backgroundColor: '#28a745',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              fontSize: '14px',
              cursor: 'pointer'
            }}>
             添加定时器
          </button>
        </div>
      </div>

      {/* 定时器列表 */}
      <div style={{ maxHeight: '300px', overflowY: 'auto' }}>
        {timersLoading ? (
          <div style={{ 
            textAlign: 'center', 
            color: '#666', 
            padding: '20px',
            fontSize: '14px'
          }}>
             加载定时器中...
          </div>
        ) : timers.length === 0 ? (
          <div style={{ 
            textAlign: 'center', 
            color: '#666', 
            padding: '20px',
            fontSize: '14px'
          }}>
             还没有定时器，添加一个开始使用吧！
          </div>
        ) : (
          timers.map((timer) => (
            <div
              key={timer.id}
              style={{
                padding: '12px',
                border: '1px solid #ddd',
                borderRadius: '6px',
                marginBottom: '8px',
                backgroundColor: timer.isCompleted ? '#d4edda' : 'white'
              }}>
              <div style={{ 
                display: 'flex', 
                justifyContent: 'space-between', 
                alignItems: 'center',
                marginBottom: '8px'
              }}>
                <h4 style={{ 
                  margin: 0, 
                  fontSize: '14px',
                  color: timer.isCompleted ? '#155724' : '#333'
                }}>
                  {timer.name}
                </h4>
                <button
                  onClick={() => deleteTimer(timer.id)}
                  style={{
                    padding: '4px 8px',
                    backgroundColor: '#dc3545',
                    color: 'white',
                    border: 'none',
                    borderRadius: '3px',
                    fontSize: '12px',
                    cursor: 'pointer'
                  }}>
                  
                </button>
              </div>
              
              <div style={{ 
                fontSize: '18px', 
                fontWeight: 'bold',
                color: timer.isCompleted ? '#155724' : '#007bff',
                marginBottom: '8px',
                textAlign: 'center'
              }}>
                {formatTime(timer.remaining)}
              </div>
              
              <div style={{ 
                display: 'flex', 
                gap: '8px',
                justifyContent: 'center'
              }}>
                <button
                  onClick={() => toggleTimer(timer.id)}
                  disabled={timer.isCompleted}
                  style={{
                    padding: '6px 12px',
                    backgroundColor: timer.isRunning ? '#dc3545' : '#28a745',
                    color: 'white',
                    border: 'none',
                    borderRadius: '4px',
                    fontSize: '12px',
                    cursor: timer.isCompleted ? 'not-allowed' : 'pointer',
                    opacity: timer.isCompleted ? 0.6 : 1
                  }}>
                  {timer.isRunning ? ' 暂停' : ' 开始'}
                </button>
                
                <button
                  onClick={() => resetTimer(timer.id)}
                  style={{
                    padding: '6px 12px',
                    backgroundColor: '#6c757d',
                    color: 'white',
                    border: 'none',
                    borderRadius: '4px',
                    fontSize: '12px',
                    cursor: 'pointer'
                  }}>
                   重置
                </button>
              </div>
              
              {timer.isCompleted && (
                <div style={{ 
                  textAlign: 'center', 
                  marginTop: '8px',
                  fontSize: '12px',
                  color: '#155724',
                  fontWeight: 'bold'
                }}>
                   已完成！
                </div>
              )}
            </div>
          ))
        )}
      </div>

      {/* 清空所有定时器 */}
      {timers.length > 0 && (
        <button
          onClick={clearAllTimers}
          style={{
            width: '100%',
            padding: '8px',
            backgroundColor: '#dc3545',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            fontSize: '12px',
            cursor: 'pointer',
            marginTop: '12px'
          }}>
           清空所有定时器
        </button>
      )}

      <div style={{ marginTop: 12, fontSize: '11px', color: '#666' }}>
         提示：定时器完成后会显示系统通知提醒，状态会自动保存
      </div>
    </div>
  )
}
